import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const UserSchema = new mongoose.Schema({
    tel: String, // 电话号码，唯一
    passwd: String, // 用户密码
    nickname: String, //
    avatar: String, // 头像
    mail: String, // edu邮箱
    schoolId: String, // 所属学校
    college: String, // 所属学院
    grade: String, // 年级
    gender: String, // 性别
    major: String, // 专业
    sId: String, // 学号
    idImgs: Array, // 证件图片
    realName: String, // 真实姓名
    isAuth: Boolean, // 是否实名认证
    code: String, // 手机验证码
    captcha: String, // 验证码
    money: {type: Number, default: 0}, // 余额
    madeMoney: {type: Number, default: 0}, // 赚到的钱
    point: {type: Number, default: 0}, // 积分
    leftPoint: {type: Number, default: 0}, // 累计的积分
    bgImage: String, // 背景图
    birthday: String, // 生日
    createTime: Number, //
    frozenTo: {type: Number, default: 0}, // 被冻结到某天
});

UserSchema.methods.saveUser = function (user, cb) {
    user.createTime = moment().unix();
    user.point = 0;
    user.leftPoint = 0;
    user.money = 0;
    user.madeMoney = 0;
    this.model('user').insertMany([user], cb);
};

UserSchema.methods.getUsers = function (query, cb) {
    const { current = 1, pageSize = 10, ...leftQuery } = query;
    const userModel = this.model('user');
    userModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        userModel.find(leftQuery, { passwd: 0 }).sort({frozenTo: 1}).skip((current - 1) * pageSize).limit(pageSize).exec((err, users) => cb(err, users, count, hasMore));
    });
};

UserSchema.methods.getAllUsers = function (query, cb) {
    // this.model('user').find(query, { tel: 1, _id: 0 }, cb);
    this.model('user').find(query, cb);
};

UserSchema.methods.getUser = function (query, cb) {
    this.model('user').findOne(query, cb);
};

UserSchema.methods.updateUser = function (user, cb) {
    const _id = user._id;
    delete user._id;
    this.model('user').findOneAndUpdate({ _id }, { $set: user }, cb);
};

UserSchema.methods.removeUsers = function (userIds, cb) {
    this.model('user').remove({ _id: { $in: userIds } }, cb);
};

export default db.model('user', UserSchema);